<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entity_Category extends Core_Db_Entity {

	public function __construct() {
		parent::__construct(App::db());
		$this->setBaseTable('category');
	}

	protected function _beforeSave() {
		// perform validate
		$config = array(
			array(
				'field'   => 'name',
				'label'   => 'Name',
				'rules'   => 'required'
			)
		);

		$validator = App::lib('form_validation'); 
		$validator->set_rules($config);
		if ($validator->run() == FALSE) {
			App::objectSingleton('Entity_Session_Admin')->addError($validator->getErrors());
			throw new Exception();
		};
		
		// set parent category to null if user not choose
		if ($this->getParentCategory() < 1)
			$this->setData('parent_category', NULL);
			
		// invalidate cache
		App::objectSingleton('Entity_Category_Cache')->setIsValid(false);
	}
	
	protected function _beforeDelete() {
		// update post's parent category foreign key
		$this->_conn->query("UPDATE post SET category = NULL where category = {$this->getId()}");
		
		// update category index table
		$this->_conn->query("DELETE FROM cat_index WHERE ancestor = {$this->getId()} OR descendant = {$this->getId()}");
		
		// delete descendant category
		foreach($this->getChildCategories() as $cat) {
			$cat->delete();
		}

		// invalidate cache
		App::objectSingleton('Entity_Category_Cache')->setIsValid(false);
	}
	
	public function getChildCategories() {
		return App::object('Entity_Category')->getCollection()->addParentCategoryFilter($this->getId());
	}
}